package com.ws.hw_student.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ws.hw_student.system.entity.Student;
import com.ws.hw_student.system.service.IStudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/students")
@CrossOrigin(origins = "http://localhost") // 允许前端跨域访问
@RequiredArgsConstructor
public class StudentController {

    private final IStudentService studentService;

    // 分页查询（匹配前端参数 _page 和 _limit）
    @GetMapping
    public ResponseEntity<Map<String, Object>> getStudents(
            @RequestParam(defaultValue = "1") int _page,
            @RequestParam(defaultValue = "5") int _limit,
            @RequestParam(required = false) String q) {

        // 修正：MyBatis-Plus的Page构造函数第一个参数是当前页（从1开始）
        // 所以不需要减1，直接使用_page
        Page<Student> page = new Page<>(_page, _limit);

        // 应用搜索条件
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if (q != null && !q.isEmpty()) {
            // 在姓名、学号或其他字段中搜索
            queryWrapper.like("name", q)
                    .or()
                    .like("student_no", q);
            // 可以根据需要添加更多搜索字段
        }

        // 执行分页查询
        page = studentService.page(page, queryWrapper);

        Map<String, Object> response = new HashMap<>();
        response.put("records", page.getRecords()); // 数据列表
        response.put("total", page.getTotal());     // 总记录数
        return ResponseEntity.ok(response);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        return student != null ? ResponseEntity.ok(student) : ResponseEntity.notFound().build();
    }

    @PostMapping
    public ResponseEntity<Student> addStudent(@RequestBody Student student) {
        return studentService.save(student) ?
                ResponseEntity.ok(student) :
                ResponseEntity.badRequest().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Student> updateStudent(
            @PathVariable Integer id,
            @RequestBody Student student) {
        student.setStudentNo(id);
        return studentService.updateById(student) ?
                ResponseEntity.ok(student) :
                ResponseEntity.notFound().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(@PathVariable Integer id) {
        return studentService.removeById(id) ?
                ResponseEntity.noContent().build() :
                ResponseEntity.notFound().build();
    }
}